<%@page import="java.awt.print.Printable"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<title>_上架任务分配</title>
<script type="text/javascript">
	var row_num = 0;
	$(function() {
		$("#inputForm").validate();
	});
	function add(count,sku,errorflag,batchCode,productDate,expireDate,upnum){
		var flag = 0;
		//bug190 by zhangweize L18,L22-L23
		var errorFlag = errorflag == 'noterror' ?  "完好件":"破损件"
		$("table[name=contentTable] > tbody > tr").each(function(){
			var sku_ready = $(this).find("td").eq(1).html();
			var errorFlag_ready = $(this).find("td").eq(2).html();
			var batchCode_ready = $(this).find("td").eq(3).html();
			var productDate_ready = $(this).find("td").eq(4).html();
			var expireDate_ready = $(this).find("td").eq(5).html();		
			
			if((errorFlag == errorFlag_ready) && (sku == sku_ready) && (batchCode == batchCode_ready) 
					&& (productDate == productDate_ready) && (expireDate == expireDate_ready)){
				$(this).find("input").eq(0).val(parseInt($(this).find("input").eq(0).val())+parseInt($("#U_"+sku.replace('/', '\\/')+"_"+errorflag+"_"+batchCode+"_"+productDate+"_"+expireDate).html())) ;
				$("#U_"+sku+"_"+errorflag+"_"+batchCode+"_"+productDate+"_"+expireDate).html("0");
				flag = 1;
				return false;
			}else{
				if((errorFlag == errorFlag_ready) && (sku == sku_ready)){
					jAlert(sku + "不同批次或者效期不能再同一个上架任务中.");
					flag = 1;
					return false;
				}else{
					flag = 0;	
				}
			}
		});
		if(flag==0){
			var html = "";
			html = html +"<tr>";
			html = html +"<td>"+count+"</td>" ;
			html = html +"<td>"+sku+"</td>";
			if(errorflag=='noterror'){
				html = html +"<td name='noterror'>完好件</td>";
			}else if(errorflag=='error'){
				html = html +"<td name='error'>破损件</td>";
			}
			html = html +"<td>"+batchCode+"</td>";
			html = html +"<td>"+productDate+"</td>";
			html = html +"<td>"+expireDate+"</td>";
			var tmpid = "bodyDetail_U_" + sku + "_" + errorflag + "_" + batchCode + "_" + productDate + "_" + expireDate;
			html = html +"<td><input id="+ tmpid +" type='text' name= 'upnum_change' onkeydown=\"if(event.keyCode==13) {return false;}\" class='required digits' value="+upnum+" ></input></td>";
			html = html +"<td><a class='btn btn-danger btn-sm' name='removeRow' num='"+upnum+"'>删除</a></td>";
			html = html+"</tr>";
			$("#U_"+sku.replace('/', '\\/')+"_"+errorflag+"_"+batchCode+"_"+productDate+"_"+expireDate).html("0");
			$("#bodyDetail").append(html);
			row_num++;
			return 1; 
		}
		else {
			return 0;
		}
	}
	
	 $(function($) {
		 /**
		 * 已加载的分配商品的删除操作事件绑定。 
		 */
		$("table[name=contentTable]").on('click', "a[name='removeRow']", function() {
			var tds = $(this).parent().parent().find("td") ;
			var sku = tds.eq(1).html();//获取当前删除行的SKU
			sku = sku.replace('/', '\\/');
			//bug190 by zhangweize L61,L67
			var errorflag=tds.eq(2).html();//获取当前删除行的报损状态
			var batchCode = tds.eq(3).html();
			var productDate = tds.eq(4).html();
			var expireDate = tds.eq(5).html();
			var flag = false;//用于判定是否有未分配商品
			if(errorflag == "完好件"){
				errorflag = "noterror" ;
			}else{
				errorflag = "error" ;
			}
			 
			$("table[name=contentTable2] > tbody > tr").each(function(){
				var sku_now = $(this).find("td").eq(2).html() ;//获取循环tr的sku
				sku_now = sku_now.replace('/', '\\/');
				var batchCode_now = $(this).find("td").eq(3).html();
				var productDate_now = $(this).find("td").eq(4).html();
				var expireDate_now = $(this).find("td").eq(5).html();
				var errorflag_now = $(this).find("td").eq(8).html() ;//获取循环tr的报损状态
				if(errorflag_now == "完好件"){
					errorflag_now = "noterror" ;
				}else{
					errorflag_now = "error";
				}
				 
				if((errorflag == errorflag_now) && (batchCode == batchCode_now) && (productDate == productDate_now) && (expireDate == expireDate_now) && (sku == sku_now)){
					 
					var name = "#U_"+sku+"_"+errorflag+"_"+batchCode+"_"+productDate+"_"+expireDate;
					//$(name).html(parseInt($("#bodyDetail").find("td").find("input").val())+parseInt($(name).html()));
					$(name).html(parseInt($("#bodyDetail_" +name.replace('#','')).val())+parseInt($(name).html()));
					 
					flag = true ;
				}
				 
			});
			if(!flag){
				jAlert("未分配商品无法加载，如需继续操作该SKU请删除子任务后重新添加！","温馨提示");
			}
			$(this).parent().parent().remove();
		});
		/**
		*一件添加所有商品
		*/
		$("#addAll").click(function(){
			var trall = jQuery("#contentTable2").find("tbody").eq(0).find("tr");
			$("table[name=contentTable2] > tbody > tr").each(function(){
				var count = $(this).find("td").eq(0).html();
				var batchCode = $(this).find("td").eq(3).html();
				var productDate = $(this).find("td").eq(4).html();
				var expireDate = $(this).find("td").eq(5).html();
				var bszt = $(this).find("td").eq(8).html();
				var errorflag =null;
				if(bszt == "完好件"){
					errorflag = "noterror" ;
				}else{
					errorflag = "error" ;
				}
				var sku = $(this).find("td").eq(2).html();

				// var upnum = $(this).find("button").eq(0).attr("num") ; 
				var upnum = $(this).find("td").eq(7).html();
				var ifNum = add(count,sku,errorflag,batchCode,productDate,expireDate,parseInt(upnum));
				if (ifNum == 1) {
					$(this).find("td").eq(7).html("0");
					// $(this).find("button").eq(0).attr("num","0"); 
				}
			});
		});
		 
		/**
		*修改上架数量
		*/
		$("table[name=contentTable]").on('change',"input[name='upnum_change']",function() {
			var sl = $(this).val() ;//已分配数量
			var ysl = $(this).parent().parent().find("a").attr("num") ;//删除按钮数量
			 
			var name = "#U_" + $(this).parent().parent().find("td").eq(1).html()+"_"+$(this).parent().parent().find("td").eq(2).attr("name")+"_"+$(this).parent().parent().find("td").eq(3).html()+
			 	"_"+$(this).parent().parent().find("td").eq(4).html()+"_"+$(this).parent().parent().find("td").eq(5).html();
			name = name.replace('/', '\\/');
			var ywfpsl = $(name).parent().find("button").attr("num"); // 添加按钮数量
			var wfpsl = $(name).html().trim();  // 未分配数量
			var yfpsl = $(name).parent().find("td").eq(6).html(); // 应分配数量
			 
			if(parseInt(ysl) == parseInt(ywfpsl)){//单独添加
			 	if(parseInt(sl)>parseInt(ysl)){
			 		jAlert("数量超标","温馨提示");
			 		$(this).val(ysl);
			 		$(name).html("0");
			 	}else{
					$(name).html(parseInt(ysl)-parseInt(sl));
			 	}
			}else if(parseInt(ysl) > parseInt(ywfpsl)){
				jAlert("一键添加异常,请刷新页面再做操作","温馨提示") ;
			}else{
				if(parseInt(sl)-parseInt(ysl)>parseInt(ywfpsl)){
					jAlert("数量超标","温馨提示");
					$(this).val(ysl);
					$(name).html(ywfpsl);
				}else{
					$(name).html(parseInt(ywfpsl)-parseInt(sl)+parseInt(ysl));
				}
			}
		}) ;
	});

	function update(subTaskCode){
		$("#windowTitle").html("");
		if(subTaskCode){
			$("#windowTitle").html(subTaskCode);
		}
		if(subTaskCode){
			$.ajax({
				type:'post',
				url:'${ctx}/v2_instorageUpDispatch/loadSubDetail/'+subTaskCode,
				data:{
					subTaskCode:subTaskCode
				},
				dataType:'json',
				success:function(data) {
				    var html = "";
				    row_num = data.subItems.length;
					$.each(data.subItems, function(i) {
						html = html +"<tr>";
						html = html +"<td>"+(i+1)+"</td>" ;
						html = html +"<td>"+data.subItems[i].skuCode+"</td>";
						if(data.subItems[i].errorFlag=='noterror'){
							html = html +"<td name='noterror'>完好件</td>";
						}else if(data.subItems[i].errorFlag=='error'){
							html = html +"<td name='error'>破损件</td>";
						}
						html = html +"<td>"+data.subItems[i].batchCode+"</td>";
						html = html +"<td>"+data.subItems[i].productDate+"</td>";
						html = html +"<td>"+data.subItems[i].expireDate+"</td>";
						var tmpid = "bodyDetail_U_" + sku + "_" + errorflag + "_" + batchCode + "_" + productDate + "_" + expireDate;
						html = html +"<td><input id="+ tmpid +" type='text' class='required digits' name= 'upnum_change' onkeydown=\"if(event.keyCode==13) {return false;}\" value='"+data.subItems[i].num+"'></input></td>";
						html = html +"<td><a class='btn btn-danger btn-sm' name='removeRow' num='"+data.subItems[i].num+"'>删除</a></td>";
						html = html+"</tr>";
					});
					$("#bodyDetail").html(html);
				},
				error:function() {
					alert("网络繁忙，请稍后重试...");
				}
		   });
	   }
	}
	
	function mySubmit(){
		if($("#inputForm").valid()){
		    var rows = [];
			$.each($("#bodyDetail").children(),function(i){
				var tr = this;
				var tds = $(this).find(".required");
				var row = {
					taskCode : '${task.taskCode}',
					subTaskCode : $("#windowTitle").html(),
					skuCode : $($(tr).children().eq(1)).html(),
					errorFlag : $($(tr).children().eq(2)).attr("name"),
					batchCode: $($(tr).children().eq(3)).html(),
					productDate: $($(tr).children().eq(4)).html(),
					expireDate: $($(tr).children().eq(5)).html(),
					num : $(tds[0]).val()
				};
				console.log($(tds[0]).val());
				rows.push(row);
			});
			var billCode = $("#billCode").val() ; 
			$.ajax({
				type:'post',
				url:'${ctx}/v2_instorageUpDispatch/updateSubDetail/'+billCode+'/${task.taskCode}/'+$("#windowTitle").html(),
				data:JSON.stringify(rows),
				dataType:'json',
				contentType: "application/json",
				success:function(data) {
					if(data == false){
						alert("超过可分配数量，请重新输入...") ;
					}else{
						window.location.href = "${ctx}/v2_instorageUpDispatch/toDispatchMain/${task.id}";
					}
				},
				error:function() {
					alert("网络繁忙，请稍后重试...");
				}
		   });
	   }
	}
	
	function finishDispatch(){
		if($("#main_1").html() == '0'){
			jAlert("分配完成");
			window.location.href = "${ctx}/v2_instorageUpDispatch/finishDispatchTask/${task.id}";
		}else{
			jAlert("还有未分配的SKU.");
		}
	}
	
</script>
</head>

<body>
	<section class="content">
		<div class="row">
			<div class="col-md-12">

				<!-- Primary box -->
				<div class="box box-solid box-primary">

					<div class="box-header">
						<i class="fa fa-list"></i>
						<h3 class="box-title">已创建的分配任务</h3>
					</div>

					<div class="box-body">
						<table id="contentTable"
							class="table table-striped table-bordered table-condensed">
							<thead>
								<tr>
									<th>序号</th>
									<th>入库单号</th>
									<th>分配任务号</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								<c:forEach items="${subTasks}" var="t" varStatus="i">
									<tr>
										<td>${i.count}</td>
										<td>${task.instorageBill.billCode}</td>
										<td>${t.subTaskCode}</td>
										<td><a href="#detail" role="button" data-toggle="modal" class='btn btn-primary' onclick="update('${t.subTaskCode}')">修改</a>
										<a href="${ctx}/v2_instorageUpDispatch/delteteSubTask/${t.subTaskCode}/${task.id}" class="btn btn-danger" onclick="deleteSubTask('${t.subTaskCode}')">删除</a></td>
									</tr>
								</c:forEach>
							</tbody>
						</table>
					</div>

				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-md-12">

				<!-- Primary box -->
				<div class="box box-solid box-primary">

					<div class="box-header">
						<i class="fa fa-list"></i>
						<h3 class="box-title">未分配的商品</h3>
					</div>

					<div class="box-body">
						<table id="contentTable"
							class="table table-striped table-bordered table-condensed">
							<thead>
								<tr>
									<th>序号</th>
									<th>入库单号</th>
									<th>SKU</th>
									<th>批次号</th>
									<th>生产日期</th>
									<th>过期日期</th>
									<th>应分配数量</th>
									<th>未分配数量</th>
									<th>报损状态</th>
								</tr>
							</thead>
							<tbody id="mainBodyDetail">
								<c:forEach items="${unDispatch}" var="t" varStatus="i">
									<tr>
										<td>${i.count}</td>
										<td>${task.instorageBill.billCode}
										<input type="hidden" id="billCode" name="billCode" value="${task.instorageBill.billCode}">
										</td>
										<td>${t.sku.split("_")[0]}</td>
										<td>${(t.batchCode == "null" ? "" : t.batchCode)}</td>
										<td>${(t.productDate == "null" ? "" : t.productDate)}</td>
										<td>${(t.expireDate == "null" ? "" : t.expireDate)}</td>
										<td>${t.num}</td>
										<td id="main_${i.count}">${t.num - t.upNum}</td>
										<c:if test="${t.errorFlag eq 'noterror'}">
											<td>完好件</td>
										</c:if>
										<c:if test="${t.errorFlag eq 'error'}">
											<td>破损件</td>
										</c:if>
									</tr>
								</c:forEach>
							</tbody>
						</table>
					</div>

				</div>
			</div>
		</div>
		
		<!-- 明细窗口 -->
	<div class="modal fade"  id="detail" >
	<form id="inputForm"  method="post" class="form-horizontal">
		<div class="modal-dialog" style="height: 900px; width: 900px">
			<div class="modal-content"  >
	
		<!-- 头 -->
		<div class="modal-header">
		<span style="font-size: large; font-weight: bold;" id="windowTitle"></span>
		</div>
		<!-- 体 -->
		<div class="modal-body">
						<fieldset>
						      <div class="row">
			<div class="col-md-12">

				<!-- Primary box -->
				<div class="box box-solid box-primary">

					<div class="box-header">
						<i class="fa fa-list"></i>
						<h3 class="box-title">已分配商品</h3>
					</div>

					<div class="box-body">
						<table id="contentTable" name="contentTable"
							class="table table-striped table-bordered table-condensed">
							<thead>
								<tr>
									<th>序号</th>
									<th>SKU</th>
									<th>报损状态</th>
									<th>批次号</th>
									<th>生产日期</th>
									<th>过期日期</th>
									<th>数量</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody id="bodyDetail">
							</tbody>
						</table>
					</div>

				</div>
			</div>
		</div>
							</fieldset>	
							<div class="row">
			<div class="col-md-12">

				<!-- Primary box -->
				<div class="box box-solid box-primary">

					<div class="box-header">
						<i class="fa fa-list"></i>
						<h3 class="box-title">未分配的商品</h3>
					</div>

					<div class="box-body">
						<table id="contentTable2" name="contentTable2"
							class="table table-striped table-bordered table-condensed">
							<thead>
								<tr>
									<th>序号</th>
									<th>入库单号</th>
									<th>SKU</th>
									<th>批次号</th>
									<th>生产日期</th>
									<th>过期日期</th>
									<th>应分配数量</th>
									<th>未分配数量</th>
									<th>报损状态</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody id="bodyDetail2">
								<c:forEach items="${unDispatch}" var="t" varStatus="i">
									<c:if test="${t.num - t.upNum ne '0'}">
									<tr>
										<td>${i.count}</td>
										<td>${task.instorageBill.billCode}</td>
										<td>${t.sku.split("_")[0]}</td>
										<td>${(t.batchCode == "null" ? "" : t.batchCode)}</td>
										<td>${(t.productDate == "null" ? "" : t.productDate)}</td>
										<td>${(t.expireDate == "null" ? "" : t.expireDate)}</td>
										<td>${t.num}</td>
										<td id="U_${t.sku}_${t.errorFlag}_${t.batchCode}_${t.productDate}_${t.expireDate}">${t.num - t.upNum}
										</td>
										<c:if test="${t.errorFlag eq 'noterror'}">
											<td>完好件</td>
										</c:if>
										<c:if test="${t.errorFlag eq 'error'}">
											<td>破损件</td>
										</c:if>
										<td><button class='btn btn-info btn-sm' type="button" num ='${t.num - t.upNum}' onclick="add('${i.count}','${t.sku}','${t.errorFlag}','${t.batchCode}','${t.productDate}','${t.expireDate}','${t.num - t.upNum}')">添加</button></td>
									</tr>
									</c:if>
								</c:forEach>
							</tbody>
						</table>
					</div>

				</div>
			</div>
		</div>
		      
		</div>
		<!-- 尾 -->
		<div class="modal-footer bg-gray">
			<input class="btn btn-primary"  type="button" value="一键添加" id="addAll"/>&nbsp;
			<input id="submit_btn" class="btn btn-primary"  type="button" value="提交" onclick="mySubmit();"/>&nbsp;	
			<!-- <input id="cancel_btn" class="btn btn-primary" type="button" data-dismiss="modal" value="返回" />
				修改为重新加载页面 -->
			<input class="btn btn-primary" type="button"  value="返回" onclick="window.location.reload();"/>
		</div>
		</div>
		</div>
        </form> 
     </div>
     <div class="modal-footer bg-gray">
     <a href="#detail" role="button" data-toggle="modal" class='btn btn-primary' onclick="update()">分配任务</a>
			<%-- <a class="btn btn-primary" href="${ctx}/v2_instorageUpDispatch/createSubTask/${task.id}" >分配任务</a> --%>	
			<a class="btn btn-primary" onclick="finishDispatch()" style="margin-left: 10px; ">完成分配</a>
		</div>
	</section>
</body>
</html>
